function [var,dy]=var_select_neighbor(x,y,maxvar)

%VAR_SELECT_NEIGHBOR boosting variable selection on closet neighbor predictions
%Syntax: [var,dy]=var_select_neighbor(x,y,maxvar)
%Description: each time pick the variable that leads to the lowest
%             crossvalidated differences. x is the matrix of independent
%             variable values [ row x columns = cases x variables], y is
%             the vector/matrix of outcomes and dy is a vector of
%             differences for each of the variable selections, which are orderly returned in var.
%             maxvar is an optinal parameter setting a maximum for number of variables
%             selected.
%
%Jonas Almeida, 17 Feb 2006

n=length(x(1,:)); %number of variables;
if nargin<3;maxvar=n;end
xi=[];var=[];dy=[]; % initialize matrix of try variable values, vector of variable picks, and the corresponding differences
var_j=[1:maxvar];%variables left to pick
for i=1:maxvar
    dyj=[];
    for j=var_j
        try
        xj=[xi,x(:,j)]; %try jth additional variable
        catch
            disp(':-(')
        end
        dyj=[dyj,sum(abs(neighbors_y_cv(xj,y)-y))]; %save sum of absolute differences
    end
    % find out which one did best
    [dyi,Ind]=min(dyj);
    var=[var,var_j(Ind)];
    xi=[xi,x(:,var_j(Ind))];
    var_j(Ind)=[];
    dy=[dy,dyi];
    %disp([num2str(i),': var#',num2str(var(end)),' selected, err=',num2str(dy(end))])
end
    
        
